<template>
	<div class="register">
		<p class="register-title">挂 号 办 理</p>
		<el-form :model="register" :rules="rules" ref="registerForm" label-width="100px" class="register-ruleForm">
			<el-form-item label="患者姓名" prop="patientName" class="register-name">
				<el-input v-model="register.patientName"></el-input>
			</el-form-item>
			<el-form-item label="性别" prop="patientSex" class="register-name">
				<el-radio-group v-model="register.patientSex">
					<el-radio label="男">男</el-radio>
					<el-radio label="女">女</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="年龄" prop="patientAge" class="register-name">
				<el-input v-model="register.patientAge"></el-input>
			</el-form-item>
			<el-form-item label="手机号" prop="patientPhone" class="register-name">
				<el-input v-model="register.patientPhone"></el-input>
			</el-form-item>
			<el-form-item label="身份证号" prop="cardNumber" class="register-name">
				<el-input v-model="register.cardNumber"></el-input>
			</el-form-item>
			<el-form-item label="科室" prop="department_value">
				<el-select v-model="departmentvalue" placeholder="请选择科室" @change="handleSelectChange">
					<el-option v-for="items in register.department" :key="items.value" :label="items.text "
						:value="items.text">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="就诊医生" prop="doctor_value" class="register-certificate">
				<el-select v-model="register.doctor_value" placeholder="请选择就诊医生" @change="handleDoctor">
					<el-option v-for="items in register.doctor" :key="items.id" :label="items.name" :value="items.name">
					</el-option>
				</el-select>
			</el-form-item>
			<p v-if="register.doctor_value">
				<el-form-item label="就诊时间：" class="register-name">
					<span>{{ register.visit_date }} {{ register.visit_time }}</span>
				</el-form-item>
			</p>
			<p v-if="register.doctor_value">
				<el-form-item label="候诊号：" class="register-name">
					<span>待计算</span>
				</el-form-item>
			</p>
			<p v-if="register.doctor_value">
				<el-form-item label="挂号费：" class="register-name">
					<span>{{ register.expense }}元</span>
				</el-form-item>
			</p>
			<el-button type="primary" class="submitBtn" @click="submitForm('registerForm')">提交挂号</el-button>
			<el-button type="reset" @click="resetForm('registerForm')">重置</el-button>
		</el-form>
	</div>
</template>

<script type="text/ecmascript-6">
	import Vue from 'vue';
	import {
		debounce
	} from 'lodash';
	import {
		api
	} from '../../../global/api.js';
	export default {
		data() {
			// 验证输入身份证号格式是否正确的方法
			let checkCertificate = (rule, value, callback) => {
				// 检查是否为空值
				if (!value) {
					callback(new Error('请输入身份证号码！'));
					return;
				}

				// 检查格式是否正确
				if (!/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
					.test(
						value)) {
					callback(new Error('身份证格式不正确'));
					return;
				}

				// 可选：校验码验证（18位身份证）
				if (value.length === 18) {
					const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; // 权重因子
					const checkCode = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']; // 校验码字符集
					let sum = 0;
					for (let i = 0; i < 17; i++) {
						sum += parseInt(value[i], 10) * weights[i];
					}
					const mod = sum % 11;
					const expectedCheckCode = checkCode[mod];
					if (value[17].toUpperCase() !== expectedCheckCode) {
						callback(new Error('身份证校验码不正确'));
						return;
					}
				}

				// 如果通过所有验证，调用callback
				callback();
			};

			// 验证年龄的方法
			let checkAge = (rule, value, callback) => {
				// 检查是否为空值
				if (!value) {
					callback(new Error('请输入年龄'));
					return;
				}

				// 检查是否为数字
				if (!/^\d+$/.test(value)) {
					callback(new Error('年龄应为数字'));
					return;
				}

				// 检查年龄范围
				value = parseInt(value, 10); // 确保value是数字
				if (value <= 0 || value >= 200) {
					callback(new Error('年龄应在1到199之间！'));
					return;
				}

				// 如果通过所有验证，调用callback
				callback();
			};

			// 验证手机号的方法
			let checkPhone = (rule, value, callback) => {
				// 检查是否为空值
				if (!value) {
					callback(new Error('请输入手机号'));
					return;
				}

				// 检查是否为数字
				if (!/^\d+$/.test(value)) {
					callback(new Error('手机号应为数字'));
					return;
				}

				//检查长度是否为11位
				if (value.length !== 11) {
					callback(new Error('手机号应为11位数'));
					return;
				}

				callback();
			}

			// 验证医生的方法
			let checkDoctor = (rule, value, callback) => {
				// 检查是否为空值
				if (!value) {
					callback(new Error('请选择医生'));
					return;
				}

				callback();
			}

			return {
				register: {
					patientName: '',
					patientSex: '',
					patientAge: '',
					patientPhone: '',
					cardNumber: '',
					department: [],
					doctor: [],
					doctor_value: '',
					visit_time: '',
					expense: '',
					visit_date: '',
					department_value: '',
					dateTime: ''
				},
				departmentvalue: '',
				departmentText: '',
				departmentValue: '',
				rules: {
					patientName: [{
						required: true,
						message: '请输入患者姓名',
						trigger: 'blur'
					}],
					patientSex: [{
						required: true,
						message: '请输入患者性别',
						trigger: 'blur'
					}],
					patientAge: [{
						required: true,
						validator: checkAge,
						trigger: 'blur'
					}],
					patientPhone: [{
						required: true,
						validator: checkPhone,
						trigger: 'blur'
					}],
					cardNumber: [{
						required: true,
						validator: checkCertificate,
						trigger: 'blur'
					}],
					department_value: [{
						required: true,
						message: '请至少选择一个科室',
						trigger: 'change'
					}],
					doctor_value: [{
						required: true,
						validator: checkDoctor,
						trigger: 'change'
					}],
					visit_time: [{
						required: true,
						message: '请填写活动形式',
						trigger: 'blur'
					}]
				}
			};
		},
		created() {
			this.register.visit_time = this.compute_visitTime();
			this.register.visit_date = new Date().toISOString();
			
			// console.log(this.visit_date);
			let registerThis = this;
			registerThis.$http.get('http://localhost:8088/getAllDepartment').then((response) => {
				// 确保接口返回的数据结构正确
				if (response.data && Array.isArray(response.data)) {
					registerThis.register.department = response.data;
				} else {
					registerThis.$notify.error({
						message: '科室数据格式错误'
					});

				}
			}, (response) => {
				// 错误回调
				registerThis.$notify.error({
					message: '数据请求失败'
				});
			});
		},
		methods: {
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						// 收集表单数据
						let patientData = {
							date: this.register.visit_date, // 确保日期和时间格式正确
							name: this.register.patientName,
							sex: this.register.patientSex,
							age: this.register.patientAge,
							phone: this.register.patientPhone,
							idCard: this.register.cardNumber,
							disease: this.departmentText || '',
							position: this.departmentValue || '',
							doctor: this.register.doctor_value,
							copayFee: this.register.expense
						};

						// 发起 POST 请求提交数据
						this.$http.post('http://localhost:8088/insertPatientlist2', patientData).then((
							response) => {
							// 请求成功
							this.$notify({
								message: '挂号成功',
								type: 'success'
							});
							// 可以在这里执行一些操作，例如清空表单
							this.resetForm(formName);
							console.log(patientData)
						}).catch((error) => {
							// 请求失败
							console.error(error);
							this.$notify.error({
								message: '挂号失败，请稍后重试'
							});
						});
					} else {
						// 表单验证失败
						this.$notify.error({
							message: '表单验证失败，请检查输入'
						});
					}
				});
			},
			resetForm(formName) {
				this.$refs.registerForm.resetFields();
				this.departmentvalue = '';
				this.register.doctor_value = '';
				this.register.doctor = []; // 清空医生列表
				this.register.expense = ''; // 清空挂号费
			},
			compute_visitTime() {
				var hour = new Date().getHours();
				var minutes = new Date().getMinutes();
				var time = '';
				if (hour < 11) {
					time = '8:00 - 11:30';
				} else if (hour === 11) {
					if (minutes < 30) {
						time = '8:00 - 11:30';
					}
				} else {
					time = '14:00 - 17:30';
				}
				return time;
			},
			handleSelectChange(value) {
				const departmentlist = this.register.department.find(nurse => nurse.value === value);
				if (departmentlist) {
					this.departmentText = departmentlist.text;
					this.departmentValue = departmentlist.position;
				}
			},
			handleDoctor(doctorName) {
				const form = this.register.doctor.find(nurse => nurse.name === doctorName);
				console.log(form);
				if (form) {
					if (form.isProfessional === 'yes') {
						this.register.expense = 12;
					} else if (form.isProfessional === 'no') {
						this.register.expense = 8;
					}
				}
			}
		},
		watch: {
			departmentvalue: function() {
				let registerThis = this;
				registerThis.register.department_value = registerThis.departmentvalue;
				registerThis.register.doctor = []; // 初始化医生列表
				registerThis.register.doctor_value = ''; // 初始化医生选择值
				registerThis.register.expense = ''; // 初始化挂号费

				registerThis.$http.get('http://localhost:8088/getDoctor').then((response) => {
					const doctorList = response.body.data;

					registerThis.register.doctor = doctorList.filter(drug => drug.office == registerThis
						.departmentvalue);
				}, (response) => {
					// 错误回调
					registerThis.$notify.error({
						message: '数据请求失败'
					});
				});
			}
		}
	};
</script>

<style>
	.register .register-title {
		font-weight: bold;
		font-size: 28px;
		width: 50%;
		margin: 0 auto;
		text-align: center;
		padding-bottom: 40px;
	}

	.register-ruleForm {
		width: 30%;
		margin: 0 auto;
		padding-left: 20px;
	}

	.register-name {
		width: 315px;
	}

	.submitBtn {
		margin-left: 30px;
	}
</style>